package com.boshao.classschedule.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.boshao.classschedule.R;
import com.boshao.classschedule.listener.CalendarFragmentCallBack;
import com.boshao.classschedule.model.DaoMaster;
import com.boshao.classschedule.model.DaoMaster.DevOpenHelper;
import com.boshao.classschedule.model.DaoSession;
import com.boshao.classschedule.model.DateInfo;
import com.boshao.classschedule.model.LifeSchedule;
import com.boshao.classschedule.model.LifeScheduleDao;
import com.boshao.classschedule.model.LifeScheduleDao.Properties;
import com.boshao.classschedule.utils.TimeUtils;
import com.boshao.classschedule.utils.ViewHolder;

import de.greenrobot.dao.query.QueryBuilder;

public class TimeManagerAdapter extends BaseAdapter{
	private int mCurrentYear;
	private int mCurrentMonth;
	private int mCurrentDay;
	private int mSelectedDay;
	public List<DateInfo> mDateInfos = null;
	private int mDayOfMonth;
	private Context mContext;
	private List<LifeSchedule> mLifeSchedules;
	private static final String[] WEEKS = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; 
	private static final String DATE_FORMAT = "%d年%s月"; 
	public TimeManagerAdapter(Context context,CalendarFragmentCallBack callBack) {
		mContext = context;
		mCurrentYear = callBack.getCurrentYear();
		mCurrentMonth = callBack.getCurrentMonth();
		mCurrentDay = callBack.getCurrentDay();
		mSelectedDay = callBack.getSelectedDay();		
		mDayOfMonth = TimeUtils.getDaysOfMonth(mCurrentYear, mCurrentMonth);
		mDateInfos = initDate(mDayOfMonth,callBack.getDateInfos());
		mLifeSchedules = initLifeSchedule(mCurrentYear, mCurrentMonth,mDayOfMonth);
	}
	
	/**
	 * 初始化数据：从数据库中查询日程
	 * @param year
	 * @param month
	 * @param daysOfMonth
	 * @return
	 */
	private List<LifeSchedule> initLifeSchedule(int year,int month,int daysOfMonth){
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(mContext,"time-manager-db",null);
		SQLiteDatabase db = helper.getReadableDatabase();
		DaoMaster daoMaster = new DaoMaster(db);
		DaoSession daoSession = daoMaster.newSession();
		LifeScheduleDao dao = daoSession.getLifeScheduleDao();
		QueryBuilder<LifeSchedule> qb = dao.queryBuilder();
		String q = "%"+String.format(DATE_FORMAT,year,formatTime(month))+"%";
		qb.where(Properties.Start_date.like(q));
		List<LifeSchedule> lifeSchedules = qb.list();
		Map<Integer,Integer> wap = new HashMap<>();
		for (int i = 0,length = lifeSchedules.size(); i < length; i++) {
			LifeSchedule lifeSchedule = lifeSchedules.get(i);
			wap.put(Integer.parseInt(lifeSchedule.getStart_date().substring(8,10)),i);
		}
		List<LifeSchedule> list = new ArrayList<>(daysOfMonth);
		for(int i = 1;i <= daysOfMonth ;i++){
			if(wap.containsKey(i)){
				list.add(lifeSchedules.get(wap.get(i)));
			}else{
				list.add(null);
			}
		}
		return list;
	}
	
	/*
	 *格式化时间,2015-5-1：或者2015-05-01 
	 */
	private String formatTime(int time){
		StringBuilder sb = new StringBuilder();
		if(sb.append(time).length() == 1){
			sb.delete(0,sb.length());
			sb.append("0").append(time);
		}
		return sb.toString();
	}
	
	/**
	 * 初始化日程ListView的数据
	 * @param mDayOfMonth
	 * @param dateInfos
	 * @return
	 */
	private List<DateInfo> initDate(int mDayOfMonth, List<DateInfo> dateInfos) {
		List<DateInfo> dInfos = new ArrayList<>();
		for (int i = 0,length = dateInfos.size(); i < length; i++) {
			DateInfo dateInfo = dateInfos.get(i);
			if(dateInfo.isThisMonth()){
				dInfos.add(dateInfo);
			}
		}
		return dInfos;
	}

	@Override
	public int getCount() {
		return mDayOfMonth;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if(convertView == null){
			convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_lifeschedule_item,parent,false);
		}
		TextView tv_date = ViewHolder.get(convertView,R.id.tv_date); 
		DateInfo dateInfo = mDateInfos.get(position);
		String date = TimeUtils.getFormatDate(mCurrentYear, mCurrentMonth,dateInfo.getDate());//2015-05-10
		String weekDay = WEEKS[TimeUtils.getWeekDay(date)];
		tv_date.setText(String.format("%d月%d日  %s",mCurrentMonth,dateInfo.getDate(),weekDay));
		TextView tvNo = ViewHolder.get(convertView, R.id.tv_no_tip);
		View layout = ViewHolder.get(convertView,R.id.ll_show_life_schedule);
		TextView tvName = ViewHolder.get(convertView, R.id.tv_schedule_name);
		TextView tvTime = ViewHolder.get(convertView, R.id.tv_schedule_time);
		if(mLifeSchedules.get(position) != null){
			LifeSchedule lifeSchedule = mLifeSchedules.get(position);
			tvNo.setVisibility(View.GONE);
			layout.setVisibility(View.VISIBLE);
			tvName.setText(lifeSchedule.getActivity_name());
			tvTime.setText(lifeSchedule.getStart_time());
		}else{
			tvNo.setVisibility(View.VISIBLE);
			layout.setVisibility(View.GONE);
		}
		
		return convertView;
	}
	
	public List<LifeSchedule> getLifeSchedules(){
		return mLifeSchedules;
	}
	
	public List<DateInfo> getDateInfos() {
		return mDateInfos;
	}
		
	/**
	 * 重置日历数据,并更新UI
	 * @param currentYear
	 * @param currentMonth
	 * @param dateInfos
	 */
	public void setUpdateData(int currentYear,int currentMonth,List<DateInfo> dateInfos){
		mCurrentYear = currentYear;
		mCurrentMonth  = currentMonth;
		mDayOfMonth = TimeUtils.getDaysOfMonth(mCurrentYear, mCurrentMonth);
		mDateInfos = initDate(mDayOfMonth, dateInfos);
		mLifeSchedules = initLifeSchedule(mCurrentYear,mCurrentMonth, mDayOfMonth);
		notifyDataSetChanged();
	}
	
	/**
	 * 返回当前位置的date: 格式 为2015-01-12
	 * @param position
	 * @return
	 */
	public String getItemFormatDate(int position){
		return TimeUtils.getFormatDate(mCurrentYear,mCurrentMonth,mDateInfos.get(position).getDate());
	}
	
	
}
